﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StationUpdate
{
    public class CommonUtil
    {
        public static string StringToASCII(string s)
        {
            string ret = "";
            if (string.IsNullOrEmpty(s))
            {
                return ret;
            }
            char[] charArry = s.ToCharArray();
            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
            for (int i = 0; i < charArry.Length; i++)
            {
                int intAsciiCode = (int)asciiEncoding.GetBytes(charArry[i].ToString())[0];
                ret = ret + intAsciiCode.ToString("X");
            }
            return ret;
        }
        /// <summary>
        /// 解析开关机时间
        /// </summary>
        public static void ParseTime(int timeinfo, ref string time)
        {
            try
            {
                DateTime dt = DateTime.Now;
                int hours = 0; int minutes = 0;
                string strtimer = Convert.ToString(timeinfo, 2).PadLeft(16, '0');
                hours = Convert.ToInt32(strtimer.Substring(0, 8), 2);
                minutes = Convert.ToInt32(strtimer.Substring(8, 8), 2);
                time = dt.ToString("yyyy-MM-dd") + " " + hours.ToString().PadLeft(2, '0') + ":" + minutes.ToString().PadLeft(2, '0') + ":00";
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// 根据时间对象，生成对应BCD码
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string GetDateTimeBcdCode(DateTime time)
        {
            if (time == null) 
            {
                return "";
            }
            StringBuilder ret = new StringBuilder();
            ret.Append(time.Year.ToString().Substring(2, 2).PadLeft(2, '0'));
            ret.Append(time.Month.ToString().PadLeft(2, '0'));
            ret.Append(time.Day.ToString().PadLeft(2, '0'));
            ret.Append(time.Hour.ToString().PadLeft(2, '0'));
            ret.Append(time.Minute.ToString().PadLeft(2, '0'));
            ret.Append(time.Second.ToString().PadLeft(2, '0'));
            return ret.ToString();
        }
        /// <summary>
        /// 获取字符串长度
        /// </summary>
        /// <returns></returns>
        public static int GetStringLength(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return 0;
            }
            System.Text.Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
            byte[] bytes = encode.GetBytes(s);
            return bytes.Length;
        }
        /// <summary>
        /// 返回某个字符串中，指定长度的子串，如果指定长度的末尾是半个字，那么半个汉字不会被返回
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string GetSubStringBySubLength(string s, int subLength)
        {
            string ret = "";
            if (subLength <= 0 || string.IsNullOrEmpty(s))
            {
                return ret;
            }
            System.Text.Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
            byte[] bytes = encode.GetBytes(s);
            int len = 0;//要返回的字符串个数
            bool flag = false;//当前字节是否为前半个汉字

            for (int i = 0; i < subLength; i++)
            {
                if (bytes[i] > 127 && flag)
                {//后半个汉字
                    flag = false;
                    len++;
                }
                else if (bytes[i] > 127)
                {//前半个汉字
                    flag = true;
                }
                else
                {//非汉字及汉字标点符号
                    len++;
                }

            }

            return s.Substring(0, len);
        }
        /// <summary>
        ///  十六进制转十进制
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static int Convert16To10(string s)
        {
            return Int32.Parse(s, System.Globalization.NumberStyles.HexNumber);
        }
        public static long Convert16To1064(string s)
        {
            return Int64.Parse(s, System.Globalization.NumberStyles.HexNumber);
        }
        /// <summary>
        ///  十进制转十六进制
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string Convert10To16(int s)
        {
            return s.ToString("X");
        }
        /// <summary>
        ///  十进制转十六进制
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string Convert10To1664(long s)
        {
            return s.ToString("X");
        }
        /// <summary>
        /// 在指定的sb右边增加count个 addString
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="count"></param>
        /// <param name="addString"></param>
        /// <returns></returns>
        public static void PadRightString(ref StringBuilder sb, int count, string addString)
        {
            if (count <= 0)
            {
                return;
            }
            for (int i = 0; i < count; i++)
            {
                sb.Append(addString);
            }
            return;
        }
        /// <summary>
        /// 将米转为千米，保留一位小数
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static string ConvertMtoKm(double m) 
        {
            try
            {
                return Math.Round(m / 1000, 1).ToString("#0.0").PadLeft(5,' ');
            }
            catch (Exception ex) 
            {
                throw new Exception("将【"+m+"】米转为千米时异常，详细"+ex.Message);
            }
        }

        /// <summary>
        /// 从源串转成16进制串
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string ConvertStringToISN(string source)
        {
            string str = "";
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding("GB2312");
            byte[] bytes = chs.GetBytes(source);

            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
            }
            return str;
        }

        /// <summary>
        /// 从16进制转成中文
        /// </summary>
        /// <param name="hexstring"></param>
        /// <returns></returns>
        public static string Convert16ToChinase(string hexstring)
        {
            System.Text.Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
            byte[] b = new byte[hexstring.Length / 2];
            for (int i = 0; i < hexstring.Length / 2; i++)
            {
                b[i] = Convert.ToByte("0x" + hexstring.Substring(i * 2, 2), 16);
            }
            return encode.GetString(b);

        }

        public static string Week()
        {
            string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            return weekdays[Convert.ToInt32(DateTime.Now.DayOfWeek)] + " " + DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分");

        }
        /// <summary>
        /// 检测是否为整数
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool CheckNum(string s) 
        {
            bool ret = false;
            try
            {
                Convert.ToInt32(s);
                ret = true;
            }
            catch 
            {}
            return ret;
        }
        public static string ConvertByteTo16Str(byte[] result)
        {
            StringBuilder builder = new StringBuilder();
            foreach (byte bte in result)
            {
                builder.Append(bte.ToString("X2"));
            }
            return builder.ToString();
        }

        public static byte[] convertStringToCharArray(string strBusAllData)
        {
            byte[] charstemp = null;
            try
            {
                string strReturn = "";
                char[] chars = strBusAllData.ToArray();
                int nAllDataLen = strBusAllData.Length, j = 0;
                charstemp = new byte[nAllDataLen / 2];
                for (int n = 0; n < nAllDataLen / 2; n++)
                {
                    charstemp[n] = 0;
                    char nch1 = convertCharToInt(chars[j++]);
                    char nch2 = convertCharToInt(chars[j++]);
                    charstemp[n] = (byte)((nch1 << 4) + nch2);
                }
                strReturn = string.Concat(charstemp);
            }
            catch (Exception ex)
            {
            }
            return charstemp;
        }

        private static char convertCharToInt(char ch)
        {
            UInt16 ntemp = 0;
            try
            {
                if ((ch >= '0') && (ch <= '9'))
                {
                    ntemp = (UInt16)((UInt16)ch - 48);
                    return (char)ntemp;
                }
                if ((ch >= 'A') && (ch <= 'F'))
                {
                    ntemp = (UInt16)((UInt16)ch - 65 + 10);
                    return (char)ntemp;
                }
                if ((ch >= 'a') && (ch <= 'f'))
                {
                    ntemp = (UInt16)((UInt16)ch - 97 + 10);
                    return (char)ntemp;
                }
            }
            catch (Exception ex)
            {
            }
            return (char)ntemp;
        }

    }
}
